package com.ruoyi.safe.controller.web;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.ListType;
import com.ruoyi.common.core.domain.vo.ListItemVo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.safe.domain.ListConstruction;
import com.ruoyi.safe.domain.ListDevise;
import com.ruoyi.safe.domain.ListMaintenance;
import com.ruoyi.safe.domain.ListManage;
import com.ruoyi.safe.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 清单分类Controller
 *
 * @author buxi
 * @date 2023-11-04
 */
@RestController
@RequestMapping("/list/type")
public class ListTypeController extends BaseController {
    @Autowired
    private IListTypeService listTypeService;
    @Autowired
    private IListDeviseService listDeviseService;
    @Autowired
    private IListConstructionService listConstructionService;
    @Autowired
    private IListMaintenanceService listMaintenanceService;
    @Autowired
    private IListManageService listManageService;


    /**
     * 查询清单分类列表
     */
    @PreAuthorize("@ss.hasPermi('list:type:list')")
    @GetMapping("/list")
    public AjaxResult list(ListType listType) {
        List<ListType> list = listTypeService.selectListTypeList(listType);
        return success(list);
    }

    /**
     * 导出清单分类列表
     */
    @PreAuthorize("@ss.hasPermi('list:type:export')")
    @Log(title = "清单分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ListType listType) {
        List<ListType> list = listTypeService.selectListTypeList(listType);
        ExcelUtil<ListType> util = new ExcelUtil<ListType>(ListType.class);
        util.exportExcel(response, list, "清单分类数据");
    }

    /**
     * 获取清单分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('list:type:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(listTypeService.selectListTypeById(id));
    }

    /**
     * 新增清单分类
     */
    @PreAuthorize("@ss.hasPermi('list:type:add')")
    @Log(title = "清单分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ListType listType) {
        return toAjax(listTypeService.insertListType(listType));
    }

    /**
     * 修改清单分类
     */
    @PreAuthorize("@ss.hasPermi('list:type:edit')")
    @Log(title = "清单分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ListType listType) {
        return toAjax(listTypeService.updateListType(listType));
    }

    /**
     * 删除清单分类
     */
    @PreAuthorize("@ss.hasPermi('list:type:remove')")
    @Log(title = "清单分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(listTypeService.deleteListTypeByIds(ids));
    }

    /**
     * 获取清单分类下拉树列表
     */
    @PostMapping("/treeselect")
    public AjaxResult treeselect(@RequestBody ListType listType) {
        listType.setStatus("0");
        List<ListType> archivesTypes = listTypeService.selectListTypeList(listType);
        List<TreeSelect> treeSelects = listTypeService.buildTypeTreeSelect(archivesTypes);
        return AjaxResult.success(treeSelects);
    }

    @PostMapping("/treeselect/all")
    public AjaxResult treeselectAll(@RequestBody ListType listType) {
        // 设计清单
        List<ListDevise> listDevises = listDeviseService.selectListDeviseListAll(ListDevise.builder().status("0").build());
        // 施工清单
        List<ListConstruction> listConstructions = listConstructionService.selectListConstructionListAll(ListConstruction.builder().status("0").build());
        // 养护清单
        List<ListMaintenance> listMaintenances = listMaintenanceService.selectListMaintenanceListAll(ListMaintenance.builder().status("0").build());
        // 管理清单
        List<ListManage> listManages = listManageService.selectListManageListAll(ListManage.builder().status("0").build());
        // 清单分类
        listType.setStatus("0");
        List<ListType> archivesTypes = listTypeService.selectListTypeList(listType);
        for (int i = 0; i < archivesTypes.size(); i++) {
            if (archivesTypes.get(i).getTypeNo().startsWith("1")) {
                int index = i;
                List<ListDevise> collect = listDevises.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListDevise listDevise : collect) {
                    ListItemVo build = ListItemVo.builder().build();
                    BeanUtils.copyProperties(listDevise, build);
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            } else if (archivesTypes.get(i).getTypeNo().startsWith("2")) {
                int index = i;
                List<ListConstruction> collect = listConstructions.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListConstruction listConstruction : collect) {
                    ListItemVo build = ListItemVo.builder().build();
                    BeanUtils.copyProperties(listConstruction, build);
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            } else if (archivesTypes.get(i).getTypeNo().startsWith("3")) {
                int index = i;
                List<ListMaintenance> collect = listMaintenances.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListMaintenance listMaintenance : collect) {
                    ListItemVo build = ListItemVo.builder().build();
                    BeanUtils.copyProperties(listMaintenance, build);
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            } else if (archivesTypes.get(i).getTypeNo().startsWith("4")) {
                int index = i;
                List<ListManage> collect = listManages.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListManage listManage : collect) {
                    ListItemVo build = ListItemVo.builder()
                            .typeNo(listManage.getTypeNo())
                            .id(listManage.getId())
                            .riskLevel(listManage.getRiskLevel())
                            .dangerLevel(listManage.getDangerLevel())
                            .riskFactor(listManage.getManageBehaviors())
                            .controlMeasure(listManage.getControlMeasure())
                            .normativeBasis(listManage.getNormativeBasis())
                            .build();
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            }
        }
        List<TreeSelect> treeSelects = listTypeService.buildTypeTreeSelect(archivesTypes);
        return AjaxResult.success(treeSelects);
    }
}
